#!/usr/bin/python
# -*- coding: utf-8 -*-
import simplejson as json
import os
# from grab import Grab
# from jbotclass import jsend
from socketfuncs import send_bot_task
from config import ABS_PATH
from time import sleep
from urllib import urlopen, quote

def antispam_passed(from_user, text):
    text = text.strip()
    if 'tmradio' in from_user: return True
    if text.count("#") > 2: return False
    if not ('@tmradio' in text or '#tmradio' in text): return False
    if not (
        text.startswith('@tmradio') or 
        text.startswith('#tmradio') or 
        text.endswith('#tmradio')
        ):
        return False
    return True

max_id_file = os.path.join(ABS_PATH, 'twmaxid.txt')

q = 'tmradio'
url = "http://search.twitter.com/search.json?q={0}&lang=ru".format( quote(q) )
print ("Loading url: {0}".format(url) )
# g = Grab()
# g.setup(timeout = 60, connect_timeout = 50)
# g.go(url)
# response = str(g.response.body)
response = urlopen(url).read()
jsonData = json.loads(response)

last_max_id = None
try:
    f = open(max_id_file, 'r')
    last_max_id = int(f.read())
    f.close()
    print "last_max_id was:", last_max_id
except: pass
max_id = jsonData['max_id']
print "twitter returned max_id", max_id
results = jsonData['results']
alertJIDs = 'hakimovis@ya.ru; itramp.uln@gmail.com'
for row in results:
    id = row['id']
    if last_max_id and id>last_max_id:
        print("New message found. id:{0}".format(row.get('id_str', None)) )
        from_user = row.get('from_user', u'Неизвестно')
        text = row.get('text', u'')
        created_at = row.get('created_at', '')
        lText = text.lower()
        
        # Send twitter message to chat using jbot socket
        if text and from_user and antispam_passed(from_user, text):
            task = json.dumps({'action': 'chat', 'text': text, 'from_nickname': u'twitter.com/'+from_user})
            if not send_bot_task(task): 
                print "Socket error. Exiting."
                exit("Socket error. Jbot is down?")
            sleep(2)

        found = False
        if u'эфир' in lText and not '--' in lText:
            found = True
            if from_user in ('dugwin', 'umonkey'):
                found = True
            else:
                for word in [u'запис', u'получил', u' был']:
                    if word in lText: found = False
        if found:
            alertString = u"%s %s: %s"%(created_at, from_user, text)
            #print alertString
            for jid in alertJIDs.split(';'):
                jid = jid.strip()
                task = json.dumps({'action': 'direct', 'text': alertString, 'jid': jid})
                send_bot_task(task)
            # jsend(alertJIDs, alertString)
        #f = open("/home/ekis/tornado/messagefile.txt",'a')
        #toChat = u"twitter.com/%s: %s\n"%(from_user, text)
        #f.write(toChat.encode('utf-8'))
        #f.close()
        
if not last_max_id or last_max_id<max_id:
    f = open( max_id_file , 'w')
    f.write(str(max_id))
    f.close()
